$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_fbhttz_m")
    const dgrid1 = $NG.getCmpApi("p_form_fbhttz_d1")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    useValuesChange(() => {
        getCntCbInfoByPhid()
    }, "p_form_fbhttz_m.u_fbhtbh")

    useValuesChange(() => {
        getSupplyInfo()
    }, "p_form_fbhttz_m.u_fbsmc1")

    useValuesChange(() => {
        cntMFilter()
    }, "p_form_fbhttz_m.u_xmlby")

    useClick(() => {
        getFileId()
    }, "u_xzdrmb")

    useValuesChange(async () => {
       
    }, "p_form_fbhttz_m.u_lxsqbh")

    function getCntCbInfoByPhid() {
        const phid = mstform.getItem("u_fbhtbh").getValue()
        if (!phid) return
        $NG.execServer("getCntCbInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const data = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key: "u_fbhtmc",
                    value: data.cnt_name
                },
                {
                    key:"u_lxsqbh",
                    value:{
                        label:data.user_lxsqbh_exname,
                        value:data.user_lxsqbh
                    }
                },
                {
                    key: "u_jhkgrq",
                    value: data.user_htjhkssj
                },
                {
                    key: "u_jhwgrq",
                    value: data.user_htjhjssj
                },
                {

                    key: "u_fbs",
                    value: {
                        label: data.fbfmc_name,
                        value: data.fbsmc_phid
                    }
                },
                {
                    key: "u_ssejdw",
                    value: {
                        label: data.phid_org_name,
                        value: data.phid_org
                    }
                },
                {
                    key: "u_fbsmc",
                    value: {
                        label: data.jfdw_name,
                        value: data.jfdw_phid
                    }
                },
                {
                    key: "u_fbszrr1",
                    value: data.user_wtdlr
                },
                {
                    key: "u_htlb",
                    value: data.user_fbhtlb
                },
                {
                    key: "u_fbhtje",
                    value: data.user_fbhtje
                }, {
                    key: "u_xmchmc",
                    value: {
                        label: data.xmch_name,
                        value: data.xmch_phid
                    }
                }, {
                    key: "u_sfzdht",
                    value: data.user_sfzdht
                }
            ]
            FbchByFblx(data.user_lxsqbh)
            setHeadValues(arr)
        })
    }
"[{\"dic\":null,\"extendObjects\":{\"u_fbxmchsbh\":\"6870000000000002\",\"u_fbxmchsmc\":\"交通洞、主变运输洞、通风兼安全洞、主变通风支洞工程及爆破技术服务分包策划书\"}}]"


    // 通过立项查策划
    async function FbchByFblx(phid){
        if (!phid) return
        const res = await $NG.execServer("SELECT", { sql: `select m.u_fbxmchsbh,fbch.u_fbxmchsmc from p_form_fblx_m m left join p_form_fbch_m fbch on fbch.phid = m.u_fbxmchsbh where m.phid = '${phid}'` })
        if (res.count == 0) return
        const datas = JSON.parse(res.data)[0].extendObjects
        mstform.getItem("u_fbxmchsbh").setValue({
            label: datas.u_fbxmchsmc,
            value: datas.u_fbxmchsbh
        })
    }

    //合同根据项目ID过滤
    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log('过滤参数检查', updater);
            updater.fieldSetForm.p_form_fbhttz_m.u_xmlbe.setProps({
                onBeforeOpen: async () => {
                    var u_xmlby = getHeadValue("u_xmlby")
                    if (!u_xmlby) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                clientSqlFilter: {
                    c_descript: mstform.getItem("u_xmlby").getText()
                }
            });
        });
    }

    async function getSupplyInfo() {
        const phid = getHeadValue("u_fbsmc1")
        if (!phid) return
        const res = await $NG.execServer("getSupplyInfo", { phid })
        if (res.count == 0) return
        const datas = JSON.parse(res.data)[0].extendObjects
        console.log(`datas`, datas);
        const arr = [
            {
                key: "u_lxr",
                value: datas.cname
            },
            {
                key: "u_fbsfzr",
                value: datas.user_fbsxcfzr
            },
            {
                key: "u_fbsxcfzrsfzh",
                value: datas.user_fbsxcfzrsfz
            },
            {
                key: "u_lxdh",
                value: datas.handset
            }, {
                key: "u_hh",
                value: {
                    label: datas.taxbank_no,
                    value: datas.taxbank_id
                }
            },
            {
                key: "u_khh",
                value: datas.taxbank_name
            },
            {
                key: "u_yhzh",
                value: datas.taxaccountno
            }
        ]
        setHeadValues(arr)
    }

    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: '03f6dbc1-116c-4b12-94bf-467f61a0a68e' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()

    }

    // 表头批量赋值
    function setHeadValues(arr) {
        arr.forEach(item => {
            console.log(`执行更新`, item);
            mstform.getItem(item.key)?.setValue(item.value)
        })
    }
})